package vn.com.tiz.DocumentZ.task;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;

/**
 * Task to figure out details by calling out to YouTube GData API.  We only use public methods that
 * don't require authentication.
 * 
 */
public class GetYoutubeUrlTask extends AsyncTask<YouTubeId, ProgressUpdateInfo, Uri> {
	
	private boolean mShowedError = false;

	@Override
	protected Uri doInBackground(YouTubeId... pParams) {
		String lUriStr = null;
		String lYouTubeFmtQuality = "17";   // 3gpp medium quality, which should be fast enough to view over EDGE connection
		String lYouTubeVideoId = null;
		
		if(isCancelled())
			return null;
		
		try {
		
			//publishProgress(new ProgressUpdateInfo(mMsgDetect));
			
			//WifiManager lWifiManager = (WifiManager) OpenYouTubePlayerActivity.this.getSystemService(Context.WIFI_SERVICE);
			//TelephonyManager lTelephonyManager = (TelephonyManager) OpenYouTubePlayerActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
			
			////////////////////////////
			// if we have a fast connection (wifi or 3g), then we'll get a high quality YouTube video
//			if( (lWifiManager.isWifiEnabled() && lWifiManager.getConnectionInfo() != null && lWifiManager.getConnectionInfo().getIpAddress() != 0) ||
//				( (lTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS ||
//						
//				   /* icky... using literals to make backwards compatible with 1.5 and 1.6 */		
//				   lTelephonyManager.getNetworkType() == 9 /*HSUPA*/  ||
//				   lTelephonyManager.getNetworkType() == 10 /*HSPA*/  ||
//				   lTelephonyManager.getNetworkType() == 8 /*HSDPA*/  ||
//				   lTelephonyManager.getNetworkType() == 5 /*EVDO_0*/  ||
//				   lTelephonyManager.getNetworkType() == 6 /*EVDO A*/) 
//				  
//				 && lTelephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED) 
//			   ){
//				lYouTubeFmtQuality = "18";
//			}
			

			///////////////////////////////////
			// if the intent is to show a playlist, get the latest video id from the playlist, otherwise the video
			// id was explicitly declared.
//			if(pParams[0] instanceof PlaylistId){
//				publishProgress(new ProgressUpdateInfo(mMsgPlaylist));
//				lYouTubeVideoId = YouTubeUtility.queryLatestPlaylistVideo((PlaylistId) pParams[0]);
//			}
			
//			else if(pParams[0] instanceof VideoId){
//				lYouTubeVideoId = pParams[0].getId();
//			}
			
			//mVideoId = lYouTubeVideoId;
			
			//publishProgress(new ProgressUpdateInfo(mMsgToken));
			
			if(isCancelled())
				return null;

			////////////////////////////////////
			// calculate the actual URL of the video, encoded with proper YouTube token
			//lUriStr = YouTubeUtility.calculateYouTubeUrl(lYouTubeFmtQuality, true, lYouTubeVideoId);
			
			if(isCancelled())
				return null;

//			if(lYouTubeFmtQuality.equals("17")){
//				publishProgress(new ProgressUpdateInfo(mMsgLowBand));
//			} else {
//				publishProgress(new ProgressUpdateInfo(mMsgHiBand));
//			}

		} catch(Exception e) {
			Log.e(this.getClass().getSimpleName(), "Error occurred while retrieving information from YouTube.", e);
		}

		if(lUriStr != null){
			return Uri.parse(lUriStr);
		} else {
			return null;
		}
	}



	@Override
	protected void onPostExecute(Uri pResult) {
		super.onPostExecute(pResult);
		
//		try {
//			if(isCancelled())
//				return;
//			
//			if(pResult == null){
//				throw new RuntimeException("Invalid NULL Url.");
//			}
//			Log.i("TrungTT","url:"+pResult.toString());
//		    //mVideoView.setVideoURI(pResult);
//		    
//			if(isCancelled())
//				return;
//		    
//		    // TODO:  add listeners for finish of video
//		    //mVideoView.setOnCompletionListener(new OnCompletionListener(){
//
//				@Override
//				public void onCompletion(MediaPlayer pMp) {
//					if(isCancelled())
//						return;
//					OpenYouTubePlayerActivity.this.finish();
//				}
//		    	
//		    });
//		    
//			if(isCancelled())
//				return;
//
//			final MediaController lMediaController = new MediaController(OpenYouTubePlayerActivity.this);
//			mVideoView.setMediaController(lMediaController);
//			lMediaController.show(0);
//			//mVideoView.setKeepScreenOn(true);
//			mVideoView.setOnPreparedListener( new MediaPlayer.OnPreparedListener() {
//
//				@Override
//				public void onPrepared(MediaPlayer pMp) {
//					if(isCancelled())
//						return;
//					OpenYouTubePlayerActivity.this.mProgressBar.setVisibility(View.GONE);
//					OpenYouTubePlayerActivity.this.mProgressMessage.setVisibility(View.GONE);
//				}
//		    	
//		    });
//		    
//			if(isCancelled())
//				return;
//
//			mVideoView.requestFocus();
//			mVideoView.start();
//		} catch(Exception e){
//			Log.e(this.getClass().getSimpleName(), "Error playing video!", e);
//			
//			if(!mShowedError){
//				showErrorAlert();
//			}
//		}
	}

	private void showErrorAlert() {
		
//		try {
//			Builder lBuilder = new AlertDialog.Builder(OpenYouTubePlayerActivity.this);
//			lBuilder.setTitle(mMsgErrorTitle);
//			lBuilder.setCancelable(false);
//			lBuilder.setMessage(mMsgError);
//
//			lBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
//
//				@Override
//				public void onClick(DialogInterface pDialog, int pWhich) {
//					OpenYouTubePlayerActivity.this.finish();
//				}
//				
//			});
//
//			AlertDialog lDialog = lBuilder.create();
//			lDialog.show();
//		} catch(Exception e){
//			Log.e(this.getClass().getSimpleName(), "Problem showing error dialog.", e);
//		}
	}

	@Override
	protected void onProgressUpdate(ProgressUpdateInfo... pValues) {
		super.onProgressUpdate(pValues);
		
		//OpenYouTubePlayerActivity.this.updateProgress(pValues[0].mMsg);
	}
	
	

	
	
}
